package com.wnxy.web.servlet;

import com.wnxy.service.impl.EmployeeServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
@MultipartConfig
@WebServlet("/updateImage")
public class UpdateImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");//处理接收POST请求的乱码
        resp.setContentType("text/html;charset=UTF-8");//解决响应到浏览器的内容的乱码问题
        String imgid= req.getParameter("imgid");
        System.out.println(imgid);
        int id = 0;
        if(imgid != null && !"".equals(imgid)){
            id = Integer.parseInt(imgid);
        }
        Part file = req.getPart("myFile");
        System.out.println(file);
        //获取文件原始名
        String fileName = file.getSubmittedFileName();
        System.out.println(fileName);
        String nginxPath = "E:/MyProgarm/nginx-1.18.0/html/dongman/"+id;
        File dir = new File(nginxPath);
        if (!dir.exists()){
            dir.mkdirs(); //创建出每个员工专享的文件夹： id命名
        }
        file.write(nginxPath+"/"+fileName);
        String imgPath = "http://localhost/dongman/"+id+"/"+fileName;
        // 调用业务逻辑层更新员工头像
        EmployeeServiceImpl esi = new EmployeeServiceImpl();
        boolean flag = esi.updateImg(id, imgPath);
        if(flag){
            resp.getWriter().write("<script>alert('恭喜，头像已更新')</script>");
        }else {
            resp.getWriter().write("<script>alert('抱歉，修改头像失败')</script>");
        }
        resp.setHeader("refresh","0,url="+req.getContextPath()+"/onePage");
    }

}
